//
//  PayManager.m
//  PayFramework
//
//  Created by RubyJobs on 2018/12/7.
//  Copyright © 2018 个人. All rights reserved.
//

#import "PayManager.h"
#import <WXApi.h>
#import <AlipaySDK/AlipaySDK.h>
#import "MJExtension.h"
#import <CommonCrypto/CommonDigest.h>
#define WeChatAppKey @""
@interface PayManager ()<WXApiDelegate>
{
    //支付0.成功 1.失败
    NSString *payflag;
    NSString *shopId;
}
@end

@implementation PayManager


+ (instancetype)shareManager{
    static PayManager * manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[PayManager alloc] init];
    });
    
    return manager;
}
#pragma mark - 配置支付启动参数（微信需要配置，支付宝不需要配置）
- (void)configStartPay{
    payflag = @"0";
    shopId = @"";
    [WXApi startLogByLevel:WXLogLevelNormal logBlock:^(NSString *log) {
        NSLog(@"log : %@", log);
    }];
    //向微信注册,发起支付必须注册
//    [WXApi registerApp:WeChatAppKey universalLink:@""];
    [WXApi registerApp:WeChatAppKey enableMTA:YES];
    
}
#pragma mark - 阿里支付
- (void)getAliPaySign:(NSString *)orderId{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Identifier = [infoDictionary objectForKey:@"CFBundleIdentifier"];
    NSString *appScheme = app_Identifier;
    //调起支付
    orderId = [orderId stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[AlipaySDK defaultService] payOrder:orderId fromScheme:appScheme callback:^(NSDictionary *resultDic) {
        NSLog(@"reslut = %@",resultDic);
        if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
            payflag = @"0";
        }else{
            payflag = @"1";
            [[NSNotificationCenter defaultCenter] postNotificationName:@"aliPayNotify" object:self userInfo:@{}];
        }
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"aliPayNotify" object:self userInfo:@{}];
    }];
}
#pragma mark - 用于阿里标识
- (NSString *)aliPayLogo{
    return @"safepay";
}
#pragma mark - 打开支付宝
- (void)aliPay9:(NSURL *)url{
    // 支付跳转支付宝钱包进行支付，处理支付结果
    [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
        NSLog(@"result = %@",resultDic);
        if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
            payflag = @"0";
        }else{
            payflag = @"1";
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:@"aliPayNotify" object:self userInfo:@{}];
    }];
    
    
    // 授权跳转支付宝钱包进行支付，处理支付结果
    [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
        NSLog(@"result = %@",resultDic);
        // 解析 auth code
        NSString *result = resultDic[@"result"];
        NSString *authCode = nil;
        if (result.length>0) {
            NSArray *resultArr = [result componentsSeparatedByString:@"&"];
            for (NSString *subResult in resultArr) {
                if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                    authCode = [subResult substringFromIndex:10];
                    break;
                }
            }
        }
        NSLog(@"授权结果 authCode = %@", authCode?:@"");
    }];
}
- (BOOL)isWXInstall{
    return [WXApi isWXAppInstalled];
}
#pragma mark - 调起微信支付
- (void)getWXPay:(NSDictionary *)WXshopDic{
    NSMutableString *stamp  = [WXshopDic objectForKey:@"timestamp"];
    
    //调起微信支付
    PayReq* req             = [[PayReq alloc] init];
    req.partnerId           = [WXshopDic objectForKey:@"partnerid"];
    req.prepayId            = [WXshopDic objectForKey:@"prepayid"];
    req.nonceStr            = [WXshopDic objectForKey:@"noncestr"];
    req.timeStamp           = stamp.intValue;
    req.package             = [WXshopDic objectForKey:@"package"];
//    shopId = WXshopDic[@"orderid"];
    // 构造参数列表
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:WXshopDic[@"appid"] forKey:@"appid"];
    [params setObject:req.nonceStr forKey:@"noncestr"];
    [params setObject:req.package forKey:@"package"];
    [params setObject:req.partnerId forKey:@"partnerid"];
    [params setObject:req.prepayId forKey:@"prepayid"];
    [params setObject:stamp forKey:@"timestamp"];
    
    req.sign = WeChatAppKey;
//    req.sign                = [self createMd5Sign:params];
    
    [WXApi sendReq:req];
}
#pragma mark - WXApiDelegate
- (void)onResp:(BaseResp *)resp {

    if([resp isKindOfClass:[PayResp class]]){
        
        switch (resp.errCode) {
            case WXSuccess:
                payflag = @"0";
                break;
                
            default:
                payflag = @"1";
                break;
        }
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"WXPayNotify" object:self userInfo:@{}];
    }else {
        
    }
}
#pragma mark - 刷新微信支付后页面
- (BOOL)getPayWXReloadUrl{
    if ([payflag isEqualToString:@"0"]) {
        return YES;
    }else{
        return NO;
    }
//    NSString *tempUrl =  @"";
//
//    return [NSURL URLWithString:tempUrl];
    
}
#pragma mark - 刷新支付宝页面
- (BOOL)getPayaLiReloadUrl{
    if ([payflag isEqualToString:@"0"]) {
        return YES;
    }else{
        return NO;
    }
    
}

#pragma mark - 打开微信
- (BOOL)open9WXPay:(NSURL *)url{
    return [WXApi handleOpenURL:url delegate:self];
}

- (void)onReq:(BaseReq *)req {
    
}



- (void)version{
    NSLog(@"支付宝:'15.5.5' &&& 微信支付:'1.8.1'");
}

//创建package签名
-(NSString*) createMd5Sign:(NSMutableDictionary*)dict
{
    NSMutableString *contentString  =[NSMutableString string];
    NSArray *keys = [dict allKeys];
    //按字母顺序排序
    NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    //拼接字符串
    for (NSString *categoryId in sortedArray) {
        if (   ![[dict objectForKey:categoryId] isEqualToString:@""]
            && ![categoryId isEqualToString:@"sign"]
            && ![categoryId isEqualToString:@"key"]
            )
        {
            [contentString appendFormat:@"%@=%@&", categoryId, [dict objectForKey:categoryId]];
        }
        
    }
    //添加key字段
    [contentString appendFormat:@"key=%@", @"95be9d6244534c49a008f3fba8755830"];
    //得到MD5 sign签名
    NSString *md5Sign =[self md5:contentString];
    
    NSLog(@"------------%@",md5Sign);
    
    
    
    return [self test:md5Sign];
}

- (NSString *)test:(NSString *)str{
    NSString *testString = str;
    
    // lower case
    NSString *lowerCaseString1 = [testString lowercaseString];
    NSString *lowerCaseString2 = testString.lowercaseString;
    
    // upper case
    NSString *upperCaseString1 = [lowerCaseString1 uppercaseString];
    NSString *upperCaseString2 = lowerCaseString1.uppercaseString;
    
    NSLog(@"------------%@",upperCaseString1);
    
    return upperCaseString1;
}

// 签名
- (NSString *)genSign:(NSDictionary *)signParams
{
    // 排序
    NSArray *keys = [signParams allKeys];
    NSArray *sortedKeys = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    
    // 生成
    NSMutableString *sign = [NSMutableString string];
    for (NSString *key in sortedKeys) {
        [sign appendString:key];
        [sign appendString:@"="];
        [sign appendString:[signParams objectForKey:key]];
        [sign appendString:@"&"];
    }
    NSString *signString = [[sign copy] substringWithRange:NSMakeRange(0, sign.length - 1)];
    
    NSString *result = [self md5:signString];
    NSLog(@"--- Gen sign: %@", result);
    return result;
}
- (NSString *) md5:(NSString *) str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

@end
